package com.hx.bio.jerry;

import com.hx.http.GPRequest;
import com.hx.http.GPResponse;
import com.hx.http.GPServlet;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author Huathy
 * @date 2021-10-21 21:58
 * @description
 */
public class JerryMouse {
    private int port = 8080;
    private ServerSocket server;
    private Map<String, GPServlet> servletMapping = new HashMap<>();
    private Properties webxml = new Properties();

    private void init() {
        try {
            String WebInf = this.getClass().getResource("/").getPath();
            Class<? extends JerryMouse> aClass = this.getClass();
            Package aPackage = aClass.getPackage();
            FileInputStream fis = new FileInputStream(WebInf + "web.properties");
            webxml.load(fis);

            for (Object k : webxml.keySet()) {
                String key = k.toString();
                if (key.endsWith(".url")) {
                    String servletName = key.replace("\\.url", "");
                    String url = webxml.getProperty(key);
                    String className = webxml.getProperty(servletName + ".className");
                    // 单实例，多线程。
                    GPServlet obj = (GPServlet) Class.forName(className).newInstance();
                    servletMapping.put(url, obj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void start() {
        //1、加载配置文件，初始化ServeltMapping
        init();
        try {
            server = new ServerSocket(this.port);
            System.out.println("GP Tomcat 已启动，监听的端口是：" + this.port);
            //2、等待用户请求,用一个死循环来等待用户请求
            while (true) {
                Socket client = server.accept();
                //4、HTTP请求，发送的数据就是字符串，有规律的字符串（HTTP协议）
                process(client);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void process(Socket client) throws Exception {
        InputStream is = client.getInputStream();
        OutputStream os = client.getOutputStream();

        GPRequest request = new GPRequest(is);
        GPResponse response =  new GPResponse(os);

        String url = request.getUrl();
        if(servletMapping.containsKey(url)){
            servletMapping.get(url).service(request,response);
        }else{
            response.write("404 - Not Fount");
        }
        os.flush();
        os.close();
        is.close();
        client.close();
    }

    public static void main(String[] args) {
        new JerryMouse().start();
    }
}
